import type {SysAuthToken} from "@/api/login/types.ts";
import Settings from "@/settings.ts"
import {defineStore} from 'pinia'
import {ref, computed} from 'vue'
import {refreshToken} from "@/api/token";


/**
 *token状态管理
 */
export const useTokenStore = defineStore('tokenStore', () => {
  // 使用 ref 替代 reactive
  const token = ref<string | null>(null)
  const userId = ref<number | null>(null)
  const username = ref<string | null>(null)
  const name = ref<string | null>(null)
  const phone = ref<string | null>(null)
  const avatar = ref<string | null>(null)
  //定时器id
  let timer: number | null = null;


  // 初始化时从 localStorage 加载
  const initFromStorage = () => {
    const tokenJSON = localStorage.getItem(Settings.TOKEN_NAME)
    if (tokenJSON) {
      const tokenData = JSON.parse(tokenJSON) as SysAuthToken
      token.value = tokenData.token
      userId.value = tokenData.userId
      username.value = tokenData.username
      phone.value = tokenData.phone
      avatar.value = tokenData.avatar
      name.value = tokenData.name
    }
  }

  // 首次初始化
  initFromStorage()

  /*
  * 判断是否token存在
  * true 代表存在
  * false 代表不存在
  * */
  const isExist = computed(() => {
    return !!token.value
  })

  /**
   * 设置token
   * @param tokenRes 后端返回token对象
   */
  function setToken(tokenRes: SysAuthToken | null) {
    if (!tokenRes) {
      throw new Error('tokenRes 为空')
    }
    localStorage.setItem(Settings.TOKEN_NAME, JSON.stringify(tokenRes))
    token.value = tokenRes.token
    userId.value = tokenRes.userId
    username.value = tokenRes.username
    phone.value = tokenRes.phone
    avatar.value = tokenRes.avatar
    name.value = tokenRes.name

    //设置token刷新
    refresh(tokenRes.tokenTimeout);
  }

  // 清除 token
  function clearToken() {
    localStorage.removeItem(Settings.TOKEN_NAME)
    token.value = null
    userId.value = null
    username.value = null
    phone.value = null
    avatar.value = null
    name.value = null
  }


  /**
   *token刷新
   * @param timeout 过期时间
   */
  function refresh(timeout: number): void {
    if (timer) {
      clearTimeout(timer);
    }
    // 提前5分钟刷新token
    const refreshTime = (timeout - 300) * 1000

    timer = setTimeout(async () => {
      //清除原本token
      clearToken();
      //获取新的token
      const res = await refreshToken();
      setToken(res.data);
    }, refreshTime)
  }

  return {
    token,
    userId,
    username,
    name,
    phone,
    avatar,
    isExist,
    setToken,
    clearToken
  }
})
